package com.fieldchain.ex.fa100.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.custom.dialog.ProgressDialog;
import com.fieldchain.ex.fa100.custom.dialog.PromptDialog;
import com.fieldchain.ex.fa100.inter.SimpleCallBack;
import com.fieldchain.ex.fa100.mvp.base.MyBasePresenter;
import com.fieldchain.ex.fa100.mvp.base.MyBaseView;
import com.fieldchain.ex.fa100.ui.personal.activity.LoginActivity;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.share.ShareManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/3/23.
 */

public abstract class MyBaseFragment<T extends MyBasePresenter, V extends MyBaseView> extends Fragment implements MyBaseView {
    public View view;
    public Context mContext;
    public T presenter;
    private PromptDialog promptDialog;
    public ProgressDialog progressDialog;
    public boolean isFirst = true;
    private Unbinder unbinder;

    protected abstract void findView();

    protected abstract void setValue();

    public abstract int getLayout();

    public boolean needProgress=true;
    private boolean needReceive = false;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        needReceive=true;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            onPause();
        } else {
            Log.e("8888888",getClass().getSimpleName());
            onResume();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume",getUserVisibleHint()+"   "+getClass().getSimpleName()+"    "+isResumed());
        if (!getUserVisibleHint()) {
            return;
        }
        needReceive=true;

    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayout(), null);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        promptDialog = new PromptDialog(mContext);
        progressDialog = new ProgressDialog(mContext);
        initPresenter();
        findView();
        setValue();
        after();
        return view;
    }

    public void after() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbindDrawables(view);
        unbinder.unbind();
        HttpRequest.getInstance().clearAll();
    }

    @Override
    public void onPause() {
        super.onPause();
        needReceive=false;
        if (promptDialog != null) {
            promptDialog.dismiss();
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (null != presenter) {
            presenter.detachView();
        }

        EventBus.getDefault().unregister(this);
        mContext = null;
        presenter = null;
    }

    public void initPresenter() {
        Class c = getClass();
        Type types = c.getGenericSuperclass();
        if (types.toString().contains("<")) {
            Type[] actualTypeArguments = ((ParameterizedType) types).getActualTypeArguments();
            Class<T> tClass = (Class<T>) actualTypeArguments[0];
            try {
                presenter = tClass.newInstance();
                presenter.attachView((V) this, mContext);
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(BaseEvent event) {
        if(needReceive) {
            int type = event.getType();
            if (type == 1) {
                if (needProgress)
                    progressDialog.show();
            } else if (type == 2) {
                if (needProgress)
                    progressDialog.dismiss();
            } else if (type == 403) {
                loginShow();
            }
        }

    }

    public void loginShow() {
        Log.e("login","loginShow"+getClass().getSimpleName());
        if(promptDialog.isShowing()){
            promptDialog.cancel();
        }
        String msg;
        msg = "登录过期,请重新登录";
        if(ShareManager.getInstance().getUser()==null){
            msg="跳转登录注册页面";
        }
        promptDialog.show();
        promptDialog.setContent(msg);
        promptDialog.setRight("去登录");
        promptDialog.setListener(new SimpleCallBack() {
            @Override
            public void sure() {
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            }
        });

    }


    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }


}
